import router from './router'
import store from './store'

import { getToken } from '@/utils/auth' // 验权


const whiteList = ['/login'] // 不重定向白名单

const createRouter = function(res) {
        let menu_router = []
        if (getToken()) {
            let parents = getLevel(res.data.menus, 0)
            let childrens = getChildrens(parents, res.data.menus)
            menu_router = transForMation(childrens)
            menu_router.forEach(item => {
                router.addRoute(item)
            })
        }

    }
    //获取level为1的menu
const getLevel = (menus, level) => {
    return menus.filter(item => item.level === level)
}

//获取所有子菜单
const getChildrens = (parents, menus) => {
    parents.forEach(item => {
        item.childrens = []
        menus.forEach(menu => {
            if (item.menuId === menu.parentId) {
                item.childrens.push(menu)
            }
        })
    })
    return parents;
}

//把我们的menu数据变成和routes一样的数据表示
const transForMation = (childrens) => {
    let menu_router = []
    childrens.forEach((item) => {
        item.childrens.forEach(childrens => {
            let route = {}
            route.path = '/' + item.url + '/' + childrens.url
            route.name = childrens.title
            route.component = () =>
                import ('@/views' + route.path + '/index')
            menu_router.push(route)
        })
    })
    return menu_router;
}



router.beforeEach((to, from, next) => {
    if (getToken()) {
        if (to.path === '/login') {
            next({ path: '/' })
        } else {
            if (store.getters.roles.length === 0 && store.getters.menus.length === 0) {

                store.dispatch('GetInfo').then((res) => {
                    createRouter(res)
                    next()
                })
            } else {
                next()
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login`) // 否则全部重定向到登录页
        }
    }
})